const JwtStrategy = require('passport-jwt').Strategy,
  ExtractJwt = require('passport-jwt').ExtractJwt;
const opts = {}
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
const keys = require('./keys');
opts.secretOrKey = keys.secretOrKey;

const User = require('../models/User')

module.exports = passport => {
  passport.use(new JwtStrategy(opts, (jwt_payload, done) => {
    // console.log(jwt_payload);
    // jwt_payload内容为一个对象，是 jsonwebtoken 所使用的rule
    User.findById(jwt_payload.id)
      .then(user => {
        if (user) {
          return done(null, user);
        } else {
          return done(null, false);
          // 返回 Unauthorized status:401
        }
      })
  }));
}